package multipleValue;

import addbatch.OrderAddBatchDao;
import tools.HikariDataSourceUtils;
import tools.Order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class OrderMultipleValueDao {

    public void batchSave(List<Order> orders) {
        long time = System.currentTimeMillis();
        Timestamp createTime = new Timestamp(time);
        StringBuilder sql = new StringBuilder();
        sql.append(" insert into biz_order( user_id, status, create_time, total_cost, item_amount) values ");
        for (Order order : orders) {
            sql.append("("+order.getUserId()+","+order.getStatus()+",\"2021-05-16\","+order.getTotalCost()+","+order.getItemAmount()+"),");
        }
        try (Connection dbConnection = HikariDataSourceUtils.getConnection()){
             PreparedStatement preparedStatement = dbConnection.prepareStatement(sql.substring(0,sql.length()-1).toString());
            int r = preparedStatement.executeUpdate();
            System.out.println("batchSave success, done "+ r);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        List<Order> orders = new ArrayList<>(5000);
        for(int i=0;i<1000;i++){
            Order o = new Order();
            o.setUserId(1);
            o.setStatus((short)0);
            o.setTotalCost(0.0);
            o.setItemAmount(0);
            orders.add(o);
        }
        OrderMultipleValueDao orderMultipleValueDao = new OrderMultipleValueDao();
        for(int i=0;i<1000;i++){
            orderMultipleValueDao.batchSave(orders);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("run "+ (endTime-time)/1000.0+" s");
        //batchSave success, done 5000
        //run 7.681 s
    }
}
